'''
@Author: frinder6
@Date: 2019-09-25 14:57:40
@LastEditTime: 2019-09-25 15:14:23
@LastEditors: frinder6
@Description: 
'''
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

# 设置登录及服务器信息
mail_host = 'smtp.163.com'
mail_user = 'xxxxx@163.com'
mail_pass = 'xxxxx'
sender = 'xxxxx@163.com'
receivers = ['xxxxx@qq.com']

# 设置eamil信息
# 添加一个MIMEmultipart类，处理正文及附件
message = MIMEMultipart()
message['From'] = sender
message['To'] = receivers[0]
message['Subject'] = 'title'

content = MIMEText("Hello World!", 'plain', 'utf-8')

# 添加一个txt文本附件
with open('tmp.txt', 'r') as h:
    attachment_content = h.read()
# 设置txt参数
attachment = MIMEText(attachment_content, 'plain', 'utf-8')
# 附件设置内容类型，方便起见，设置为二进制流
attachment['Content-Type'] = 'application/octet-stream'
# 设置附件头，添加文件名
attachment['Content-Disposition'] = 'attachment;filename="tmp.txt"'

# 将内容附加到邮件主体中
message.attach(content)
message.attach(attachment)

# 登录并发送
try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print('success')
    smtpObj.quit()
except smtplib.SMTPException as e:
    print('error', e)
